import React, { Component } from "react";

// antd
import { Button, message } from "antd";

import { validate_email } from '../utils/validate';

// 接口
import { GetCode } from '../api/account';

// 定时器
let timer = null;

class Code extends Component {
  constructor(props) {
    super(props);
    this.state = {
      username: props.username,
      module: props.module,
      btn_text: "获取验证码",
      btn_loading: false,
      btn_disabled: false
    };
  }
  
  
  /**
   * 每次获取父传子数据
   */
  componentWillReceiveProps({ username }){
    this.setState({
      username
    });
  }
  

  /**
   * 组件销毁前
   */
  componentWillUnmount(){
    clearInterval(timer);
    timer = null;
  }

  // 获取验证码
  getCode = () => {
    const { username, module } = this.state;
    if (!username) {
      message.warning("请填写用户名");
      return;
    }

    if(!validate_email(username)){
      message.warning('邮箱格式非法');
      return;
    }

    this.setState({
      btn_loading: true,
      btn_text: "发送中",
    });

    GetCode({
      username,
      module
    })
      .then((res) => {
        message.success(res.data.message);
        //执行定时器
        this.countDown();
      })
      .catch((err) => {
        this.setState({
          btn_loading: false,
          btn_text: "重新获取",
        });
      });
  };


  // 倒计时
  countDown = () => {
    let sec = 60;

    this.setState({
      btn_disabled: true,
      btn_loading: false,
      btn_text: `${sec}s`
    });

    timer = setInterval(() => {
      sec--;
      if(sec <= 0){
        clearInterval(timer);
        timer = null;
        this.setState({
          btn_text: '重新获取',
          btn_disabled: false
        });

        return;
      }

      this.setState({
        btn_text: `${sec}S`
      });
    }, 1000);

  }

  render() {
    const { 
      btn_text, 
      btn_loading, 
      btn_disabled
    } = this.state;

    return (
      <Button
        type="primary"
        danger
        block
        loading={btn_loading}
        disabled={btn_disabled}
        onClick={this.getCode}
      >
        {btn_text}
      </Button>
    );
  }
}

export default Code;
